package com.googlecode.jvmpart.support;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import com.googlecode.jvmpart.proc.JvmProcessException;

public abstract class RowMapPartitioner extends AbsPartitioner{
	public Map<String, Map<String, Object>> doPartition() throws JvmProcessException {
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = null;
		try {
			conn = getConnection();
			ps = conn.prepareStatement(getQuerySql());
			setValues(ps);
			rs = ps.executeQuery();			
			Map<String, Map<String, Object>> params = new HashMap<String, Map<String, Object>>();
			int row = 1;
			while(rs.next()) {
				Map<String,Object> param = mapRow(rs, row);
				params.put(getJvmProcessName()+"_"+row++, param);
			}
			return params;
		} catch(SQLException e) {
			throw new JvmProcessException("patition error", e);
		} finally {
			try {
				if(rs!=null) rs.close();
				if(ps!=null) ps.close();
				if(conn!=null) conn.close();
			} catch(Exception e) {};
		}
	}
	public abstract Map<String, Object> mapRow(ResultSet rs, int row) throws SQLException;
	public abstract void setValues(PreparedStatement ps) throws SQLException;
	public abstract Connection getConnection() throws SQLException;
	public abstract String getQuerySql();
}
